<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>批次管理</span>
        <el-button type="primary" @click="handleAdd">添加批次</el-button>
      </div>
    </template>

    <!-- 查询表单 -->
    <el-form :inline="true" :model="queryParams" class="query-form">
      <el-form-item label="学年">
        <el-date-picker
            v-model="queryParams.academicYear"
            type="year"
            placeholder="选择学年"
            clearable
            style="width: 150px"
            value-format="YYYY"
        />
      </el-form-item>
      <el-form-item label="困难等级">
        <el-select v-model="queryParams.difficultyLevel" placeholder="请选择等级" clearable style="width: 150px">
          <el-option label="一般困难" :value="1" />
          <el-option label="困难" :value="2" />
          <el-option label="特别困难" :value="3" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        v-loading="loading"
        border
    >
      <el-table-column label="学年" align="center" header-align="center" min-width="150">
        <template #default="scope">
          {{ formatAcademicYear(scope.row.academicYear) }}
        </template>
      </el-table-column>
      <el-table-column label="困难等级" align="center" header-align="center" min-width="130">
        <template #default="scope">
          <el-tag v-if="scope.row.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="scope.row.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="申请开始时间" align="center" header-align="center" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.applyStart) }}
        </template>
      </el-table-column>
      <el-table-column label="申请截止时间" align="center" header-align="center" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.applyDeadline) }}
        </template>
      </el-table-column>
      <el-table-column label="登记截止时间" align="center" header-align="center" min-width="180">
        <template #default="scope">
          {{ formatDate(scope.row.registerDeadline) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250" fixed="right" align="center">
        <template #default="scope">
          <el-button link type="primary" @click="handleDetail(scope.row)">查看详情</el-button>
          <el-button link type="primary" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button link type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.limit"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        @update:current-page="(val) => queryParams.page = val"
        @update:page-size="(val) => queryParams.limit = val"
        style="margin-top: 20px; justify-content: flex-end"
    />

    <!-- 查看详情对话框 -->
    <el-dialog v-model="detailVisible" title="批次详情" width="700px">
      <el-descriptions :column="2" border>
        <el-descriptions-item label="学年" :span="2">
          {{ formatAcademicYear(detailData.academicYear) }}
        </el-descriptions-item>
        <el-descriptions-item label="困难等级" :span="2">
          <el-tag v-if="detailData.difficultyLevel === 1" type="info">一般困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 2" type="warning">困难</el-tag>
          <el-tag v-else-if="detailData.difficultyLevel === 3" type="danger">特别困难</el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="申请开始时间" :span="2">
          {{ formatDate(detailData.applyStart) }}
        </el-descriptions-item>
        <el-descriptions-item label="申请截止时间" :span="2">
          {{ formatDate(detailData.applyDeadline) }}
        </el-descriptions-item>
        <el-descriptions-item label="登记截止时间" :span="2">
          {{ formatDate(detailData.registerDeadline) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间" :span="2">
          {{ formatDateTime(detailData.createTime) }}
        </el-descriptions-item>
      </el-descriptions>
      
      <template #footer>
        <el-button type="primary" @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 新增对话框 -->
    <el-dialog v-model="addVisible" title="添加批次" width="600px">
      <el-form :model="addForm" label-width="120px" ref="addFormRef" :rules="addRules">
        <el-form-item label="学年" prop="academicYear">
          <el-date-picker
              v-model="addForm.academicYear"
              type="year"
              placeholder="选择学年"
              style="width: 100%"
              value-format="YYYY"
          />
        </el-form-item>
        <el-form-item label="困难等级" prop="difficultyLevel">
          <el-select v-model="addForm.difficultyLevel" placeholder="请选择困难等级" style="width: 100%">
            <el-option label="一般困难" :value="1" />
            <el-option label="困难" :value="2" />
            <el-option label="特别困难" :value="3" />
          </el-select>
        </el-form-item>
        <el-form-item label="申请开始时间" prop="applyStart">
          <el-date-picker
              v-model="addForm.applyStart"
              type="date"
              placeholder="选择申请开始时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="申请截止时间" prop="applyDeadline">
          <el-date-picker
              v-model="addForm.applyDeadline"
              type="date"
              placeholder="选择申请截止时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="登记截止时间" prop="registerDeadline">
          <el-date-picker
              v-model="addForm.registerDeadline"
              type="date"
              placeholder="选择登记截止时间"
              style="width: 100%"
              value-format="YYYY-MM-DD"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="addVisible = false">取消</el-button>
        <el-button type="primary" @click="submitAdd">确定</el-button>
      </template>
    </el-dialog>
  </el-card>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { _getBatchList, _deleteBatch, _saveBatch } from '@/api/batch'
import { ElMessage, ElMessageBox } from 'element-plus'

const router = useRouter()

// 查询条件
const queryParams = ref({
  page: 1,
  limit: 10,
  academicYear: '',
  difficultyLevel: null
})

// 表格数据
const tableData = ref([])
const total = ref(0)
const loading = ref(false)

// 详情对话框
const detailVisible = ref(false)
const detailData = ref({})

// 新增对话框
const addVisible = ref(false)
const addFormRef = ref(null)
const addForm = ref({
  academicYear: '',
  difficultyLevel: null,
  applyStart: '',
  applyDeadline: '',
  registerDeadline: ''
})

// 新增表单验证规则
const addRules = {
  academicYear: [
    { required: true, message: '请选择学年', trigger: 'change' }
  ],
  difficultyLevel: [
    { required: true, message: '请选择困难等级', trigger: 'change' }
  ],
  applyStart: [
    { required: true, message: '请选择申请开始时间', trigger: 'change' }
  ],
  applyDeadline: [
    { required: true, message: '请选择申请截止时间', trigger: 'change' }
  ],
  registerDeadline: [
    { required: true, message: '请选择登记截止时间', trigger: 'change' }
  ]
}

// 格式化学年（2024 -> 2024-2025）
const formatAcademicYear = (year) => {
  if (!year) return '-'
  return `${year}-${year + 1}`
}

// 格式化日期（只显示年月日）
const formatDate = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
}

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '-'
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 查询列表
const getList = () => {
  loading.value = true
  _getBatchList(queryParams.value).then(res => {
    if (res.code === 200) {
      tableData.value = res.data.records || []
      total.value = res.data.total || 0
    } else {
      ElMessage.error(res.message || '查询失败')
    }
  }).catch(err => {
    console.error('查询失败:', err)
    ElMessage.error('查询失败')
  }).finally(() => {
    loading.value = false
  })
}

// 查询按钮
const handleQuery = () => {
  queryParams.value.page = 1
  getList()
}

// 重置按钮
const resetQuery = () => {
  queryParams.value = {
    page: 1,
    limit: 10,
    academicYear: '',
    difficultyLevel: null
  }
  getList()
}

// 查看详情按钮
const handleDetail = (row) => {
  detailData.value = { ...row }
  detailVisible.value = true
}

// 添加按钮
const handleAdd = () => {
  addForm.value = {
    academicYear: '',
    difficultyLevel: null,
    applyStart: '',
    applyDeadline: '',
    registerDeadline: ''
  }
  addVisible.value = true
  // 清空表单验证
  if (addFormRef.value) {
    addFormRef.value.clearValidate()
  }
}

// 编辑按钮 - 跳转到编辑页面
const handleEdit = (row) => {
  router.push(`/batch/edit/${row.id}`)
}

// 删除按钮
const handleDelete = (row) => {
  ElMessageBox.confirm(
      `确认删除 ${formatAcademicYear(row.academicYear)} 学年的批次吗？`,
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(() => {
    _deleteBatch(row.id).then(res => {
      if (res.code === 200) {
        ElMessage.success('删除成功')
        getList()
      } else {
        ElMessage.error(res.message || '删除失败')
      }
    }).catch(err => {
      console.error('删除失败:', err)
      ElMessage.error('删除失败')
    })
  }).catch(() => {
    // 用户取消删除
  })
}

// 提交新增
const submitAdd = () => {
  addFormRef.value.validate((valid) => {
    if (valid) {
      const submitData = {
        academicYear: Number(addForm.value.academicYear),
        difficultyLevel: addForm.value.difficultyLevel,
        applyStart: addForm.value.applyStart,
        applyDeadline: addForm.value.applyDeadline,
        registerDeadline: addForm.value.registerDeadline
      }
      
      _saveBatch(submitData).then(res => {
        if (res.code === 200) {
          ElMessage.success('添加成功')
          addVisible.value = false
          getList()
        } else {
          ElMessage.error(res.message || '添加失败')
        }
      }).catch(err => {
        console.error('添加失败:', err)
        ElMessage.error('添加失败')
      })
    }
  })
}

// 分页变化
const handlePageChange = (page) => {
  queryParams.value.page = page
  getList()
}

const handleSizeChange = (size) => {
  queryParams.value.limit = size
  queryParams.value.page = 1
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  
  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }

  .query-form {
    margin-bottom: 20px;
  }
}

// 修复固定列与普通列之间的边框线
:deep(.el-table__fixed-right) {
  &::before {
    content: '';
    position: absolute;
    left: 0;
    top: 0;
    bottom: 0;
    width: 1px;
    background-color: var(--el-table-border-color);
    z-index: 1;
  }
}
</style>

